import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';

import 'package:get/get.dart' hide MultipartFile, FormData;
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:xin_he/utils/xin_he_user_data.dart';
import '../../../service/xin_he_reqest.dart';
import '../../../service/xin_he_url_class.dart';
import '../../../utils/xin_he_toast.dart';
import 'xin_he_edit_prifile_state.dart';

class XinHeEditPrifileLogic extends GetxController {
  final XinHeEditPrifileState state = XinHeEditPrifileState();

  // final TextEditingController editingController = TextEditingController();
  // ImagePicker获取内容后返回的对象是XFile
  XFile? upImage;
  late File _upFile;
  final ImagePicker _imagePicker = ImagePicker();

  TextEditingController nameController = TextEditingController();
  TextEditingController sexController = TextEditingController();
  TextEditingController phoneController = TextEditingController();



  @override
  void onInit() {
    super.onInit();

    state.name.value = xinHeUserData.userDetailInfo.value?.name??'';
    state.phone.value = xinHeUserData.userDetailInfo.value?.mobile??'';
    state.sex.value = xinHeUserData.userDetailInfo.value?.gender == 1?'男':'女';
    state.avatar.value = xinHeUserData.userDetailInfo.value?.iconPath??'';

    nameController     = TextEditingController(text: state.name.value);
    sexController = TextEditingController(text: state.sex.value);
    phoneController = TextEditingController(text: state.phone.value);
  }

  @override
  void onReady() {
    super.onReady();


  }

  savePassword() {

  }

  //取消键盘
  void closeKeyboard(){
    if (Get.focusScope?.hasPrimaryFocus == true) {
      Get.focusScope?.unfocus();
    }
  }

  ///输入框输入更改
  void inputChange(String value){

    state.inputContent.value = value;
    state.name.value = value;

  }

  void onInputEditCompleteAction() async{

    closeKeyboard();
    if(state.inputContent.value.isEmpty) {
      XinHeToast.center('请输入内容');
      return;
    }


  }

  selectedAvatarImage() async {
    XFile? image = await _imagePicker.pickImage(
      source: ImageSource.gallery,
      imageQuality: 90,
      // maxWidth: 2000,

    );
    if (image != null) {
      upImage = image;

      // _upFile = File(image.path);
      // List<int>  imageBytes = await _upFile!.readAsBytes();
      // String base64 = base64Encode(imageBytes);


      state.upImagePath.value = upImage!.path;


      uploadToAli(upImage!.path, true);


    }
  }


  uploadToAli(String filePath, bool isUp) async{

    Map<String, dynamic> upMap = {};
    var name = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length);
    upMap['file'] = await MultipartFile.fromFile(filePath,filename: name);


    FormData formData  = FormData.fromMap(upMap);


    Dio dio = Dio(BaseOptions(
        headers: {'Content-Type': 'multipart/form-data;boundary=----------'}));
    String urlss = "${XinHeHostUrlClass.hostUrl}/alibaba/uploadPhoto";
    var res = await dio.post(urlss, data: formData);


    dynamic dataObj;
    if(res.statusCode == 200){
      if (res.data is Map) {
        dataObj = res.data;
      } else {
        dataObj = json.decode(res.data.toString()) ?? {};
      }

      if(dataObj['code'] == 0){

        String upUrl = dataObj['data'];

        state.avatar.value = upUrl;

      }

    }

  }


  saveEdittingProfile() async {

    int sexValue = 1;
    if(state.sex.value == '女' ){
      sexValue = 2;
    }

    Map<String,dynamic> map = {
      'gender':sexValue,
      'iconPath':state.avatar.value,
      'userId':xinHeUserData.userId,
      'name':state.name.value,

    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/member/editMemberApp',params: map,isPost: true,isPostAndwwwForm: true);

    if(!result.result|| result.data['code'] != 0){
      XinHeToast.center(result.data['message']);
      return ;
    }
    XinHeToast.center('修改个人信息成功');

    xinHeUserData.updateAllData();

  }

}
